﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Omu.ValueInjecter;
using Xiucai.BPM.Core;
using Xiucai.Common;
using Xiucai.Common.Data;
using Xiucai.Common.Data.Filter;
using Xiucai.BPM.Core.Bll;
using Xiucai.BPM.Core.Model;
using System.Text;
namespace Xiucai.BPM.Admin.status_ybq.ashx
{
    /// <summary>
    /// YBQ 的摘要说明
    /// </summary>
    public class YBQ : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<YbqData>(context) { CurrentContext = context, Action = context.Request["Action"] };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<YbqData>>(json);
                rpm.CurrentContext = context;
            }
            int k = 0;

            switch (rpm.Action)
            {
                case "ybqNums":

                    int uid = PublicMethod.GetInt(rpm.Request("uid"));
                    if (uid == 0)
                        context.Response.Write(DevConfigBll.Instance.YBQShortNames(SysVisitor.Instance.CurrentUser.KeyId));
                    else
                        context.Response.Write(DevConfigBll.Instance.YBQShortNames(uid));
                    break;
                case "myharm":
                    context.Response.Write(DevConfigBll.Instance.YBQHarms(SysVisitor.Instance.CurrentUser.KeyId));
                    break;
                case "count":
                    int ulevel = PublicMethod.GetInt(rpm.Request("ulevel"));
                    int alevel = PublicMethod.GetInt(rpm.Request("alevel"));
                    object st = rpm.Request("stime");
                    object et = rpm.Request("etime");
                    string harms = rpm.Request("harms");
                    context.Response.Write(DevConfigBll.Instance.YBQHarmsCount(ulevel, alevel, st, et, harms));
                    break;
                case "single":
                    var devsID = PublicMethod.GetInt(rpm.Request("devID"));
                    var chID = PublicMethod.GetInt(rpm.Request("chID"));
                    var result = JsonDataForSingleChannel(devsID, chID, 1, 50, rpm.Filter);
                    context.Response.Write(result);
                    break;
                //JsonDataForEasyUIdataGridAVG
                case "avgday":
                    var devIDday = PublicMethod.GetInt(rpm.Request("devID"));
                    context.Response.Write(JsonDataForEasyUIdataGridAVGWhere(devIDday, rpm.Pageindex, rpm.Pagesize, rpm.Filter, "d"));
                    break;
                case "avgmonth":
                    var devIDdaym = PublicMethod.GetInt(rpm.Request("devID"));
                    context.Response.Write(JsonDataForEasyUIdataGridAVGWhere(devIDdaym, rpm.Pageindex, rpm.Pagesize, rpm.Filter, "m"));
                    break;
                case "avgxun":
                    var devIDdayx = PublicMethod.GetInt(rpm.Request("devID"));
                    context.Response.Write(JsonDataForEasyUIdataGridAVGWhere(devIDdayx, rpm.Pageindex, rpm.Pagesize, rpm.Filter, "x"));
                    break;
                default:
                    var devID = PublicMethod.GetInt(rpm.Request("devID"));
                    context.Response.Write(JsonDataForEasyUIdataGrid(devID, rpm.Pageindex, rpm.Pagesize, rpm.Filter));
                    break;
            }
        }


        private string JsonDataForEasyUIdataGrid(int devID, int pageindex, int pagesize, string filterJSON)
        {
            //数据权限条件
            string where = "devID=" + devID;
            if (filterJSON != "")
            {
                where = FilterTranslator.ToSql(filterJSON) + " and " + where;
            }
            var pcp = new ProcCustomPage("t_ybqStatus")
            {
                KeyFields = "keyid",
                PageIndex = pageindex,
                PageSize = pagesize,
                OrderFields = "updateTime desc",
                WhereString = where
            };
            int recordCount;
            DataTable dt = DbUtils.GetPageWithSp(pcp, out recordCount);
            return JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt);
        }

        private string JsonDataForEasyUIdataGridAVG(int devID, int pageindex, int pagesize, string filterJSON, string tablename)
        {
            //数据权限条件
            string where = "devID=" + devID;
            if (filterJSON != "")
            {
                where = FilterTranslator.ToSql(filterJSON) + " and " + where;
            }
            var pcp = new ProcCustomPage(tablename)
            {
                KeyFields = "updateTime",
                PageIndex = pageindex,
                PageSize = pagesize,
                OrderFields = "updateTime desc",
                WhereString = where
            };
            int recordCount;
            DataTable dt = DbUtils.GetPageWithSp(pcp, out recordCount);
            return JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt);
        }
        //解决条件问题
        private string JsonDataForEasyUIdataGridAVGWhere(int devID, int pageindex, int pagesize, string filterJSON, string type)
        {
            //数据权限条件
            string where = "devID=" + devID;
            if (filterJSON != "")
            {
                where = FilterTranslator.ToSql(filterJSON) + " and " + where;
            }
            int startIndex, endIndex;
            startIndex = (pageindex - 1) * pagesize + 1;
            endIndex = pageindex * pagesize;
            StringBuilder strSql = new StringBuilder();
            if (type == "d")
            {
                strSql.Append("SELECT * FROM ( ");
                strSql.Append(" SELECT ROW_NUMBER() OVER (");
                strSql.Append("order by T.updateTime desc");
                strSql.Append(")AS Row, T.*  from (SELECT devID, CONVERT(varchar(10), updateTime, 120) AS updateTime, SUM(ch0) AS ch0, SUM(ch1) AS ch1, SUM(ch2) AS ch2, SUM(ch3) AS ch3 from (select * from t_ybqstatus");
                strSql.Append(" WHERE " + where);
                strSql.Append(") mt group by devID,convert(varchar(10),[updateTime],120))  T ) TT");
                strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            }
            else if (type == "m")
            {
                strSql.Append("SELECT * FROM ( ");
                strSql.Append(" SELECT ROW_NUMBER() OVER (");
                strSql.Append("order by T.updateTime desc");
                strSql.Append(")AS Row, T.*  from (SELECT devID, CONVERT(varchar(7), updateTime, 120) AS updateTime, SUM(ch0) AS ch0, SUM(ch1) AS ch1, SUM(ch2) AS ch2, SUM(ch3) AS ch3 from (select * from t_ybqstatus");
                strSql.Append(" WHERE " + where);
                strSql.Append(") mt group by devID,convert(varchar(7),[updateTime],120))  T ) TT");
                strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);

            }
            else if (type == "x")
            {
                strSql.Append("SELECT * FROM ( ");
                strSql.Append(" SELECT ROW_NUMBER() OVER (");
                strSql.Append("order by T.updateTime desc");
                strSql.Append(")AS Row, T.*  from (SELECT devID, CONVERT(varchar(7), updateTime, 120)+'-01' AS updateTime, SUM(ch0) AS ch0, SUM(ch1) AS ch1, SUM(ch2) AS ch2, SUM(ch3) AS ch3 from (select * from t_ybqstatus where day(updateTime)<=10");
                strSql.Append(" and " + where);
                strSql.Append(") y group by devID,convert(varchar(7),[updateTime],120) ");
                strSql.Append(" union SELECT devID, CONVERT(varchar(7), updateTime, 120)+'-11' AS updateTime, SUM(ch0) AS ch0, SUM(ch1) AS ch1, SUM(ch2) AS ch2, SUM(ch3) AS ch3 from (select * from t_ybqstatus where day(updateTime) >10 and day(updateTime)<=20");
                strSql.Append(" and " + where);
                strSql.Append(") y group by devID,convert(varchar(7),[updateTime],120) ");
                strSql.Append(" union SELECT devID, CONVERT(varchar(7), updateTime, 120)+'-21' AS updateTime, SUM(ch0) AS ch0, SUM(ch1) AS ch1, SUM(ch2) AS ch2, SUM(ch3) AS ch3 from (select * from t_ybqstatus where day(updateTime)>20");
                strSql.Append(" and " + where);
                strSql.Append(") y group by devID,convert(varchar(7),[updateTime],120) ");
                strSql.Append(") T ) TT");
                strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);

            }
            int recordCount;
            DataTable dt = Xiucai.Common.Data.SqlServer.SqlEasy.ExecuteDataTable(strSql.ToString());
            strSql.Clear();
            if (type == "d")
            {
                strSql.Append("select count(*) from ( SELECT devID FROM (select * FROM t_ybqstatus ");
                strSql.Append(" where " + where);
                strSql.Append(") a group by devID,convert(varchar(10),[updateTime],120)) mt ");
            }
            else if (type == "m")
            {
                strSql.Append("select count(*) from ( SELECT devID FROM (select * FROM t_ybqstatus ");
                strSql.Append(" where " + where);
                strSql.Append(") a group by devID,convert(varchar(7),[updateTime],120)) mt ");

            }
            else if (type == "x")
            {
                strSql.Append("select count(*) from (SELECT  convert(varchar(7),[updateTime],120)+'-01' as updateTime,devID FROM (select * from t_ybqstatus where day(updateTime)<=10");
                strSql.Append(" and " + where);
                strSql.Append(") y group by devID,convert(varchar(7),[updateTime],120) ");
                strSql.Append(" union SELECT  convert(varchar(7),[updateTime],120)+'-11' as updateTime,devID FROM (select * from t_ybqstatus where day(updateTime)>10 and day(updateTime)<=20");
                strSql.Append(" and " + where);
                strSql.Append(") y group by devID,convert(varchar(7),[updateTime],120) ");
                strSql.Append(" union SELECT  convert(varchar(7),[updateTime],120)+'-21' as updateTime,devID FROM (select * from t_ybqstatus where day(updateTime)>20");
                strSql.Append(" and " + where);
                strSql.Append(" ) y group by devID,convert(varchar(7),[updateTime],120) ");
                strSql.Append(") mt ");
            }
            //int recordCount = 0;
            object o = Xiucai.Common.Data.SqlServer.SqlEasy.ExecuteScalar(strSql.ToString());
            recordCount = int.Parse(o.ToString());
            return JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt);
        }


        private string JsonDataForSingleChannel(int devID, int chID, int pageindex, int pagesize, string filterJSON)
        {
            //数据权限条件
            string where = "devID=" + devID;

            //if (SysVisitor.Instance.IsAdmin)
            //{
            //}
            //else
            //{
            if (filterJSON != "")
            {
                where = FilterTranslator.ToSql(filterJSON) + " and " + where;
            }
            //}
            var pcp = new ProcCustomPage("t_ybqStatus")
            {
                KeyFields = "keyid",
                PageIndex = pageindex,
                PageSize = pagesize,
                OrderFields = "updateTime desc",
                ShowFields = "updateTime, ch" + chID,
                WhereString = where
            };
            int recordCount;
            DataTable dt = DbUtils.GetPageWithSp(pcp, out recordCount);
            return JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt);
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}